package com.emenu;

import java.util.ArrayList;
import java.util.List;
 
import com.emenu.application.StaticObject;
import com.emenu.bean.Localparm;
import com.emenu.bean.Menu;
import com.emenu.bean.PubPrinter;
import com.emenu.bean.PubPrinterTable;
import com.emenu.bean.PubSeries;
import com.emenu.bean.PubSeriesGroup;
import com.emenu.bean.PubTable;
import com.emenu.bean.PubTimer;
import com.emenu.bean.SubMenu;
import com.emenu.bean.User;
import com.emenu.common.CM;
import com.emenu.common.GetFunRightList;
import com.emenu.common.GetWebServiceData;
import com.emenu.common.JsonUntil;
import com.emenu.common.RSStrFromJsonText;
import com.emenu.common.SaveMenuImg;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class LoginProgress  extends Activity {
	/** 进度条 */
	private ProgressBar pBar;
	private TextView tv;
	
	public static final String PREFS_NAME = "jpVerFile";
	public static final String SET_NAME = "jpSetFile";
	private Intent intent;
	StaticObject SO;
	private String tempwsdl;
	private String istest = "0";// 默认正式版
	private String islocaldata = "0";// 数据是否写入sd卡文件
	private SharedPreferences settings;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loginprogress);
		
		findViewsById();
		
		SO = (StaticObject) getApplication();
		settings = getSharedPreferences(SET_NAME, Activity.MODE_WORLD_READABLE
				| Activity.MODE_WORLD_WRITEABLE | Activity.MODE_APPEND);

		tempwsdl = settings.getString("url", "");
		istest = settings.getString("systype", "0");
		islocaldata = settings.getString("localdata", "0");
		 
		// 异步处理
		new DownloadProcess().execute((Void) null);
	}
	
	/** 视图 样式 */
	private void findViewsById() {

		pBar = (ProgressBar) findViewById(R.id.progress_bar);
		

	}
	/**
	 * 异步处理
	 */
	public class DownloadProcess extends AsyncTask<Void, Integer, String> {

		// 执行onPreExecute()完后立即调用
		@Override
		protected String doInBackground(Void... params) {
			// 调用webService初始化数据
			// 下载
			List<Localparm> Parmlist = new ArrayList<Localparm>();
			List<User> Userlist = new ArrayList<User>();
			List<Menu> Menulist = new ArrayList<Menu>();
			List<SubMenu> subMenulist = new ArrayList<SubMenu>();
			List<PubTable> tablelist = new ArrayList<PubTable>();
			List<PubTimer> PubTimerlist = new ArrayList<PubTimer>();
			List<PubSeries> PubSerieslist = new ArrayList<PubSeries>();
			List<PubSeriesGroup> PubSeriesGrouplist = new ArrayList<PubSeriesGroup>();
			List<PubPrinter> PubPrinterlist = new ArrayList<PubPrinter>();
			List<PubPrinterTable> PubTableListlist = new ArrayList<PubPrinterTable>();

			String parmjson;
			String userjson;
			String menujson;
			String submenujson;
			String tablejson;
			String PubTimerjson;
			String PubSeriesjson;
			String PubSeriesGroupjson;
			String Pubprinterjson;
			String Pubprintertablejson;

			try {
				// 从sd卡文件读json字符串,否则从webservice获取数据
				if (istest.equals("1")) {
					// 参数下载
					parmjson = RSStrFromJsonText.readDate("parmjson.json");
					publishProgress(10);

					// 用户下载
					userjson = RSStrFromJsonText.readDate("userjson.json");
					publishProgress(20);

					// menu下载
					menujson = RSStrFromJsonText.readDate("menujson.json");
					publishProgress(30);

					// submenu下载
					submenujson = RSStrFromJsonText
							.readDate("submenujson.json");
					publishProgress(40);

					// PubTable下载
					tablejson = RSStrFromJsonText.readDate("tablejson.json");
					publishProgress(50);

					// PubTimer下载
					PubTimerjson = RSStrFromJsonText
							.readDate("PubTimerjson.json");
					publishProgress(60);
					// PUB_SERIES下载
					PubSeriesjson = RSStrFromJsonText
							.readDate("PubSeriesjson.json");
					// PUB_SERIES下载
					PubSeriesGroupjson = RSStrFromJsonText
							.readDate("PubSeriesGroupjson.json");
					// Pub_printer下载
					Pubprinterjson = RSStrFromJsonText
							.readDate("Pubprinterjson.json");
					
					// Pub_printertable下载
					Pubprintertablejson = RSStrFromJsonText
							.readDate("Pubprintertablejson.json");
					
					publishProgress(70);

				} else {

					// 参数下载
					parmjson = GetWebServiceData
							.WSJson(tempwsdl,"select code,name,parmvalue from local_parm where code in('100000','200002','100008') ")
							.replaceAll("\\\\", "\\\\\\\\");
					
					publishProgress(10);

					// 用户下载
					userjson = GetWebServiceData
							.WSJson(tempwsdl,"select code,password,name,dinner_code,sex,industryNo,"
									+ "is_operate,is_posmanager,status "
									+ "from Sys_user where status=1");
					publishProgress(20);

					// menu下载
					menujson = GetWebServiceData
							.WSJson(tempwsdl,"select code,name,picoldver,picnewver,picpath,visible,"
									+ "remark,status from  pub_menu where status=1")
							.replaceAll("\\\\", "\\\\\\\\");
					
					publishProgress(30);

					// submenu下载
					submenujson = GetWebServiceData
							.WSJson(tempwsdl,"SELECT a.code,a.menu_code,a.name,a.PantryInteral,a.GarnishInteral,"
									+ "a.helpcode,a.tag_code,b.name tag_name,a.menutype,a.rljtype,a.defaultamount,a.minamount,"
									+ "a.hitamount,a.dianpincode,a.price,a.is_Special,a.SpecialPrice,a.rebate,"
									+ "a.is_alter,a.alter_integral,a.AdditionalPrint,a.picoldver,a.picnewver,"
									+ "a.picpath,a.upcode,a.is_Node,a.is_Serise,a.visible,a.remark,a.status "
									+ " from Pub_submenu a,pub_tag b where  a.tag_code=b.code and a.status=1")
							.replaceAll("\\\\", "\\\\\\\\");
					publishProgress(40);

					// PubTable下载
					tablejson = GetWebServiceData
							.WSJson(tempwsdl,"select a.id,a.code,a.name,a.helpcode,a.dinner_code,a.table_type,b.name table_typename,"
									+ " a.MaxCount,a.MinCount,a.price from Pub_table a,pub_tabletype b "
									+ "where a.table_type=b.code and a.status=1")
							.replaceAll("\\\\", "\\\\\\\\");
					
					publishProgress(50);

					// PubTimer下载
					PubTimerjson = GetWebServiceData.WSJson(tempwsdl,
							"select code,name,c1,c2,c3 from pub_timer")
							.replaceAll("\\\\", "\\\\\\\\");
					
					publishProgress(60);
					// PUB_SERIES下载
					PubSeriesjson = GetWebServiceData
							.WSJson(tempwsdl,"select a.id,a.series_code,a.seriesgroupcode,"
									+ "a.submenu_code,a.amount,b.name submenu_name "
									+ "from pub_series a ,pub_submenu b "
									+ "where a.submenu_code=b.code")
							.replaceAll("\\\\", "\\\\\\\\");
					
					// PUB_SERIES下载
					PubSeriesGroupjson = GetWebServiceData
							.WSJson(tempwsdl,"select id,code,name,isselect,selectcount from Pub_SeriesGroup")
							.replaceAll("\\\\", "\\\\\\\\");
					
					// Pub_printer下载
					Pubprinterjson = GetWebServiceData
							.WSJson(tempwsdl,"select id,code,printdesc,printaddress from Pub_printer where status=1")
							.replaceAll("\\\\", "\\\\\\\\");
					
					// Pub_printertable下载
					Pubprintertablejson = GetWebServiceData
							.WSJson(tempwsdl,"select a.id,a.print_code,a.table_code ,b.printdesc,b.printaddress "
									+ " from Pub_printertable a,Pub_printer b where a.print_code = b.code "
									+ "and b.status=1").replaceAll("\\\\",
									"\\\\\\\\");
					
					publishProgress(70);

					if (islocaldata.equals("1")) {
						RSStrFromJsonText.saveFileToSDCard("parmjson.json",
								parmjson);
						RSStrFromJsonText.saveFileToSDCard("userjson.json",
								userjson);
						RSStrFromJsonText.saveFileToSDCard("menujson.json",
								menujson);
						RSStrFromJsonText.saveFileToSDCard("submenujson.json",
								submenujson);
						RSStrFromJsonText.saveFileToSDCard("tablejson.json",
								tablejson);
						RSStrFromJsonText.saveFileToSDCard("PubTimerjson.json",
								PubTimerjson);
						RSStrFromJsonText.saveFileToSDCard(
								"PubSeriesjson.json", PubSeriesjson);
						RSStrFromJsonText.saveFileToSDCard(
								"PubSeriesGroupjson.json", PubSeriesGroupjson);
						RSStrFromJsonText.saveFileToSDCard(
								"Pubprinterjson.json", Pubprinterjson);
						RSStrFromJsonText
								.saveFileToSDCard("Pubprintertablejson.json",
										Pubprintertablejson);
					}
 				}

				Parmlist = JsonUntil.getLocalParmList(parmjson);
				Userlist = JsonUntil.getUserList(userjson);
				Menulist = JsonUntil.getMenuList(menujson);
				tablelist = JsonUntil.getPubTableList(tablejson);
				subMenulist = JsonUntil.getSubMenuList(submenujson);
				PubTimerlist = JsonUntil.getPubTimerList(PubTimerjson);
				PubSerieslist = JsonUntil.getPubSeriesList(PubSeriesjson);
				PubSeriesGrouplist = JsonUntil
						.getPubSeriesGroupList(PubSeriesGroupjson);
				PubPrinterlist = JsonUntil.getPubPrinterList(Pubprinterjson);

				PubTableListlist = JsonUntil
						.getPubPrinterTableList(Pubprintertablejson);
			} catch (Exception e) {
				e.printStackTrace();
			}

			publishProgress(80);
			
			if (istest.equals("1")) {
				SO.setSubMenuList(subMenulist);	
			}else{
			// 图片保存到版本信息保存到SharedPreferences
			SharedPreferences sp = getSharedPreferences(PREFS_NAME,
					Activity.MODE_WORLD_READABLE
							| Activity.MODE_WORLD_WRITEABLE
							| Activity.MODE_APPEND);
			SharedPreferences.Editor editor = sp.edit();
			List<SubMenu> newsubMenulist = new ArrayList<SubMenu>();
			// 下载图片保存在本地相同目录
			try {
				for (SubMenu submenu : subMenulist) {

					String imgurl = submenu.getPicpath();

					// 本地文件xml上的版本号
					String setver = sp.getString(submenu.getName(), "");

					String newver = submenu.getPicnewver();
					if ((imgurl.length() > 0) && !(setver.equals(newver))) {

						editor.putString(submenu.getName(),
								submenu.getPicnewver());

						String imgbit = GetWebServiceData.WSImage(tempwsdl,imgurl);

						SaveMenuImg.saveMyBitmap(submenu.getName(), imgurl,
								submenu.getPicnewver(), imgbit);

						submenu.setPicoldver(newver);
					}
					newsubMenulist.add(submenu);
				}
				editor.commit();

			} catch (Exception e) {

				e.printStackTrace();
			}
			SO.setSubMenuList(newsubMenulist);
			}
			publishProgress(90);

			// 置入全局变量

			SO.setParmList(Parmlist);
			SO.setUserList(Userlist);
			SO.setMenuList(Menulist);
			
			SO.setPubTableList(tablelist);
			SO.setPub_timerList(PubTimerlist);
			SO.setPubSeriesList(PubSerieslist);
			SO.setPubSeriesGroupList(PubSeriesGrouplist);
			// 功能项右边内容
			SO.setFunBeanList(GetFunRightList.getList());
			// 当前市别
			SO.setStaticTimeCode(CM.getTimeCode(PubTimerlist));
			SO.setPubPrinterList(PubPrinterlist);
			SO.setPubPrinterTableList(PubTableListlist);

			publishProgress(100);

			return "全部资源下载完成";
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// 计算还在进行时在用户界面显示进度
			pBar.setProgress(values[0]);
			tv.setText(String.valueOf(values[0]));
		}

		// doInBackground后执行
		// result 的得自于doInBackgroun
		@Override
		protected void onPostExecute(String result) {
			tv.setText(result + ",100");
			alertFinish();	
			intent = new Intent();
			
			intent.setClass(LoginProgress.this, Login.class);
			//停2秒转入登陆页面
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// 启动Activity
			startActivity(intent);
		}

		@Override
		protected void onPreExecute() {
			// 在UI线程上调用任务后立即执行，实例进度条和百分比
			tv = (TextView) findViewById(R.id.tv);			
		}

	}

	private void alertFinish() {

		Toast.makeText(this, "全部资源下载完成", Toast.LENGTH_SHORT).show();
	} 
	 
}
